package com.bjbn.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bjbn.bean.Organization;
import com.bjbn.entity.DataSyncLog;
import com.bjbn.entity.Organize;
import com.bjbn.mapper.DataSyncLogMapper;
import com.bjbn.mapper.OrganizeMapper;
import com.bjbn.service.KafkaProducerService;
import com.bjbn.service.OrganizationService;
import com.bjbn.service.OrganizeService;
import com.bjbn.util.SSLUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;


@Service
@Slf4j
public class OrganizationServiceImpl implements OrganizationService {

    @Autowired
    private OrganizeService organizeService;

    @Autowired
    private OrganizeMapper organizeMapper;

    @Autowired
    private DataSyncLogMapper dataSyncLogMapper;

    @Autowired
    private KafkaProducerService kafkaProducerService;

    @Value("${gdairport-sso-url}")
    private String gdAirportSsoUrl;



    @Override
    public List<Organization> getOrganizationList(String modifiedDate) {
        LocalDateTime now = LocalDateTime.now().minusMinutes(5);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 格式化时间
        String todayZeroTime = now.format(formatter);
        if (modifiedDate != null) {
            todayZeroTime = modifiedDate;
        }
        String url = gdAirportSsoUrl + "maxkey-mgt-api/api/idm/Organization/.search?r=1&pageNumber=1&pageSize=2000";
        url = url + "&modifiedDate=" + todayZeroTime;
        HttpRequest request = HttpUtil
                .createGet(url)
                .setConnectionTimeout(5000)
                .timeout(10000)
                .header("Authorization", "Basic MTEwOTE1OTkyNDE2NTc3MTI2NDp5RkIzTVRRd05ESXdNalV4TkRBMk16ZzNORGN6Vlg=")
                .setSSLSocketFactory(SSLUtils.getSSLSocketFactory());

        HttpResponse response0 = request.execute();

        if (response0.getStatus() == 200) {
            JSONObject res = JSONObject.parseObject(response0.body());
            if (res.getInteger("code") == 0) {
                JSONObject data = res.getJSONObject("data");
                JSONArray rows = data.getJSONArray("rows");
                return rows.toJavaList(Organization.class);
            }
        }

        return null;
    }


    @Override
    public void updateOrganizationAll(String modifiedDate) {
        List<Organization> organizations = getOrganizationList(modifiedDate);
        updateOrganization(organizations);
    }

    @Override
    public void updateOrganization(List<Organization> organizations) {
        // 将数据推送到kafka队列
        kafkaProducerService.sendBatchMessages("IAC_ORGANIZATION_UPDATE_DATA_OUT", organizations);

        Map<String, Organization> map = new HashMap<>();
        for (Organization organization : organizations) {
            map.put(organization.getId(), organization);
        }

        for (Organization organization : organizations) {
            if (organization.getParentId() != null) {
                Organization parent = map.get(organization.getParentId());
                if (parent == null) {
                    // 更新该节点
                    updateOrganize(organization);
                    System.out.println("更新该节点：" + organization.getId());
                    // 递归查找子节点 并更新子节点
                    updateChild(organization.getId(), organizations);
                }
            }
        }
    }


    private void updateOrganize(Organization organization) {
        // 从数据库查找该节点的父节点
        Organize parentOrganize = organizeService.getItemById(organization.getParentId());
        Organize old = organizeService.getItemById(organization.getId());
        Organize organize = new Organize();
        organize.setId(organization.getId());
        organize.setParentId(parentOrganize == null ? "-1" : parentOrganize.getId());
        organize.setCategory(organization.getType());
        organize.setEnCode(organization.getOrgCode());
        organize.setFullName(organization.getOrgName());
        organize.setOrganizeIdTree(parentOrganize == null ? organization.getId() : parentOrganize.getOrganizeIdTree() + "," + organization.getId());
        organize.setEnabledMark(organization.getStatus() == 1 ? 1 : 0);
        organize.setCreatorTime(old != null ? old.getCreatorTime() : java.sql.Timestamp.valueOf(LocalDateTime.now()));
        organize.setCreatorUserId(old != null ? old.getCreatorUserId() : "349057407209541");
        if (old != null) {
            organize.setLastModifyTime(java.sql.Timestamp.valueOf(LocalDateTime.now()));
            organize.setLastModifyUserId("349057407209541");
        }
        organize.setTenantId("0");
        organizeMapper.insertOrUpdate(organize);
        DataSyncLog dataSyncLog = new DataSyncLog();
        dataSyncLog.setBeforeChange(JSONObject.toJSONString(old));
        dataSyncLog.setAfterChange(JSONObject.toJSONString(organize));
        dataSyncLog.setType("organize");
        dataSyncLog.setCreateTime(java.sql.Timestamp.valueOf(LocalDateTime.now()));
        dataSyncLogMapper.insert(dataSyncLog);
    }


    private void updateChild(String id, List<Organization> organizations) {

        for (Organization organization : organizations) {
            if (organization.getParentId() != null) {
                if (organization.getParentId().equals(id)) {
                    // 更新该节点
                    updateOrganize(organization);
                    System.out.println("更新该节点：" + organization.getId() + " 父级节点：" + id);
                    // 递归查找子节点 并更新子节点
                    updateChild(organization.getId(), organizations);
                }
            }
        }

    }


}
